#include "threadPool.h"
#include <ctype.h>
#include <sys/socket.h>
#include "factory.h"
typedef struct trans_train{
    int type;
    int length;
    char contxt[4096];
}trans_train_t;
int recvn(int netfd, void *pstart, int len) {
    int total = 0;
    int ret;
    char *p = (char *)pstart;
    while (total < len) {
        ret = recv(netfd, p + total, len - total, 0);
        if (ret == 0) {
            printf("对方关闭连接\n");
            close(netfd);
            return -1;
        } else if (ret < 0) {
            perror("recv");
            return -1;
        }
        total += ret;
    }
    return 0;
}
int deal(int netfd,char* client_ip) {
    int epfd = epoll_create(1);
    epollAdd(epfd,netfd);
    struct epoll_event readyset[1024];
    //连接数据库
    MYSQL *mysql = NULL;
    if (mysqlConnect(&mysql) != 0) {
        printf(" 数据库连接失败\n");
        return -1;
    }
    printf("数据库连接成功\n");

    // 初始化目录栈
    Link_list_t catalog;
    if (init_list(&catalog) != 0) {
        printf(" 目录栈初始化失败\n");
        return -1;
    }
    printf(" 初始化目录栈成功\n");
    //--------------------------------------------------------
    char user[1024] = {0};
    int login_flag = 0;
    char stackPath[1024] = {0};
    char ls_result[4096] = {0};
    while(1){
        int readyNum =  epoll_wait(epfd,readyset,1024,-1);
      //  printf("readyNum = %d\n",readyNum);
        if (readyNum < 0) {
            perror("epoll_wait");
            return -1;
        }
        for(int i = 0;i < readyNum;i++){
            if(readyset[i].data.fd == netfd){
                trans_train_t train;
                bzero(&train, sizeof(train));

                // 先收 type 和 length，再收内容
                recvn(netfd, &train.type, sizeof(int));
                recvn(netfd, &train.length, sizeof(int));
                recvn(netfd, train.contxt, train.length);
                char returnStr[1024] = {0};

                printf("接收到命令: %d %s\n", train.type, train.contxt);
                dealOrder(mysql,netfd,&catalog,train.type,train.contxt,returnStr,user,&login_flag,stackPath,ls_result,client_ip);

                printf("%s\n",returnStr);

                int ret =  send(netfd,returnStr,strlen(returnStr)+1,0);
                ERROR_CHECK(ret,-1,"send");
            }
        }
    }
    return 0;
}
